package com.yj.auto.core.jfinal.base;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.yj.auto.Constants;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.base.online.SessionUser;
import com.yj.auto.plugin.table.DataTableUtil;
import com.yj.auto.plugin.table.model.Columns;
import com.yj.auto.plugin.table.model.DataTables;
import com.yj.auto.plugin.table.model.Order;
import com.yj.auto.utils.ModelUtil;

public abstract class BaseController extends Controller {
	public static final String VIEW_ROOT = Constants.SYS_VIEW_ROOT;
	public static final String responseKey = "responseModel";

	protected SessionUser getSu() {
		SessionUser su = this.getSessionAttr(Constants.SYS_SESSION_USER);
		return su;
	}

	protected Integer getSuId() {
		Integer uid = 0;
		SessionUser su = getSu();
		if (null != su) {
			uid = su.getId();
		}
		return uid;
	}

	protected void renderResponse(boolean success, String msg, Object data) {
		ResponseModel<Object> res = new ResponseModel<Object>(success, msg);
		res.setData(data);
		renderJson(res);
	}

	protected void renderResponse(boolean success, Object data) {
		ResponseModel<Object> res = new ResponseModel<Object>(success);
		res.setData(data);
		renderJson(res);
	}

	protected <T> List<T> getBeans(Class<T> modelCls, String modelName) {
		return ModelUtil.getBeans(this, modelCls, modelName);
	}

	protected String getParaDecode(int idx) throws UnsupportedEncodingException {
		String s = getPara(idx);
		if (StrKit.isBlank(s)) {
			return s;
		}
		return URLDecoder.decode(s, Constants.SYS_ENCODING);
	}

	public Integer[] getParaValuesToInt() {
		String para = this.getPara();
		if (StrKit.isBlank(para))
			return null;
		String[] values = para.split(Const.DEFAULT_URL_PARA_SEPARATOR);
		Integer[] result = new Integer[values.length];
		for (int i = 0; i < result.length; i++)
			result[i] = Integer.parseInt(values[i]);
		return result;
	}

	protected <T extends BaseEntity> DataTables<T> getDataTable(QueryModel query, BaseService<T> srv) {
		DataTables<T> dt = DataTableUtil.getDataTableByJson(this.getPara("dtJson"));
		if (null == dt)
			return null;
		List<Columns> cls = dt.getColumns();
		List<Order> ols = dt.getOrder();
		StringBuffer sort = new StringBuffer();
		for (Order od : ols) {
			int cidx = od.getColumn();
			if (sort.length() > 1) {
				sort.append(",");
			}
			sort.append(cls.get(cidx).getName()).append(" ").append(od.getDir());
		}

		// 重新设置相关的page分页属性

		// System.out.println("PageNumber=" + query.getPageNumber()
		// + " pageSize=" + query.getPageSize() + " Start="
		// + dt.getStart());
		query.setSize(dt.getLength());// 设置分页大小
		query.setPage(dt.getCurrentPage());// 设置页码
		query.setOrderby(sort.toString());
		Page page = srv.paginate(query);
		dt.setRecordsTotal(page.getTotalRow());
		dt.setRecordsFiltered(page.getTotalRow());
		dt.setData(page.getList());
		return dt;
	}

	protected <T extends BaseEntity> ResponseModel<String> _delete(BaseService<T> srv) {
		Integer[] id = getParaValuesToInt();
		boolean success = false;
		if (null != id || id.length > 0) {
			success = srv.delete(id);
		}
		return renderDelete(success, srv);
	}

	// protected <T extends BaseEntity> ResponseModel<String> _delete(BaseService<T>
	// srv, String... dataType) {
	// Integer[] id = getParaValuesToInt();
	// boolean success = false;
	// if (null != id || id.length > 0) {
	// success = srv.delete(id, dataType);
	// }
	// return renderDelete(success, srv);
	// }

	protected <T extends BaseEntity> ResponseModel<String> renderDelete(boolean success, BaseService<T> srv) {
		ResponseModel<String> res = new ResponseModel<String>(success);
		res.setMsg("选中" + srv.getDao().getTableRemark() + "删除" + (res.isSuccess() ? "成功" : "失败"));
		renderJson(res);
		return res;
	}

	protected <T extends BaseEntity> ResponseModel<String> renderSaveOrUpdate(boolean success, BaseService<T> srv) {
		ResponseModel<String> res = new ResponseModel<String>(success);
		res.setMsg("保存" + srv.getDao().getTableRemark() + (res.isSuccess() ? "成功" : "失败"));
		renderJson(res);
		return res;
	}

	protected void initAttaMap(Model model, String... keys) {
		if (null == keys || keys.length < 1)
			return;
		Map<String, Integer[][]> files = new HashMap<String, Integer[][]>();
		for (String key : keys) {
			List<Integer> adds = new ArrayList<Integer>();
			List<Integer> dels = new ArrayList<Integer>();
			String addStr = getPara(key);
			if (StrKit.notBlank(addStr)) {
				String[] ss = addStr.split(",");
				for (String s : ss) {
					if (StrKit.notBlank(s))
						adds.add(Integer.valueOf(s));
				}
			}

			String delStr = getPara(key + "_del");
			if (StrKit.notBlank(delStr)) {
				String[] ss = delStr.split(",");
				for (String s : ss) {
					if (StrKit.notBlank(s))
						dels.add(Integer.valueOf(s));
				}
			}
			files.put(key, new Integer[][] { adds.toArray(new Integer[adds.size()]), dels.toArray(new Integer[dels.size()]) });
		}
		model.put(Constants.MODEL_ATTA_MAP, files);
	}
}
